
# /bin/bash
# set -xeuo pipefail
set -euo pipefail

VERSION=${VERSION:-0.1.0}
APPLICATION=${APPLICATION:-scorpio}
PROJECT_DIR=$(cd $(dirname $0);cd ../;pwd)
IMAGES_DIR=${PROJECT_DIR}/images/scorpio

UV_DEFAULT_INDEX=${UV_DEFAULT_INDEX:-"https://mirrors.aliyun.com/pypi/simple"}
cd $IMAGES_DIR

echo "更新环境变量PATH..."
export PATH="$PATH:/usr/local/bin"
# env
# which docker

# 步骤1：构建基础镜像 python-base:3.12-slim
BASE_IMAGE_NAME=python-base:3.12-slim
# 检查基础镜像是否已经存在
N=$(docker images -q ${BASE_IMAGE_NAME} | wc -l)
if [ $N -gt 0 ]; then
  echo "$(date "+%Y-%m-%d %H:%M:%S") 🔍 基础镜像${BASE_IMAGE_NAME}已存在，跳过构建步骤"
else
  echo "$(date "+%Y-%m-%d %H:%M:%S") 开始构建基础镜像${BASE_IMAGE_NAME}"
  pwd
  docker build --force-rm=true --no-cache=true \
        --build-arg="UV_DEFAULT_INDEX=${UV_DEFAULT_INDEX}" \
        -t ${BASE_IMAGE_NAME} -f Dockerfile.base .

  if [ $? -ne 0 ]; then
    echo "$(date "+%Y-%m-%d %H:%M:%S") ❌ 基础镜像${BASE_IMAGE_NAME}创建失败!"
    exit 1
  fi
  echo "$(date "+%Y-%m-%d %H:%M:%S") ✅ 基础镜像${BASE_IMAGE_NAME}创建成功!"
fi

# 复制必要的脚本和配置文件
echo "$(date "+%Y-%m-%d %H:%M:%S") 📁 复制scripts到目录: ${IMAGES_DIR}"
cp -rf ${PROJECT_DIR}/scripts ${IMAGES_DIR}

if [ ! -d ${IMAGES_DIR}/scorpio ]; then
  echo "$(date "+%Y-%m-%d %H:%M:%S") 📁 创建scorpio目录: ${IMAGES_DIR}/scorpio"
  mkdir ${IMAGES_DIR}/scorpio
fi

echo "$(date "+%Y-%m-%d %H:%M:%S") 📁 复制项目文件到目录: ${IMAGES_DIR}/scorpio"
cp -r ${PROJECT_DIR}/{pyproject.toml,scorpio_config_sample.json,uv.toml,py} ${IMAGES_DIR}/scorpio

pwd

# 步骤2：构建最终的scorpio镜像
IMAGE_NAME=scorpio:09.05
echo "$(date "+%Y-%m-%d %H:%M:%S") 开始构建最终容器镜像${IMAGE_NAME}"
docker build --force-rm=true --no-cache=true \
      --build-arg="VERSION=${VERSION}" \
      --build-arg="UV_DEFAULT_INDEX=${UV_DEFAULT_INDEX}" \
      --build-arg="DB_AGENT_DIR=${PROJECT_DIR}" \
      -t ${IMAGE_NAME} -f Dockerfile .

if [ $? -eq 0 ]; then
  echo "$(date "+%Y-%m-%d %H:%M:%S") ✅ 容器镜像${IMAGE_NAME}已创建成功!"
else
  echo "$(date "+%Y-%m-%d %H:%M:%S") ❌ 容器镜像${IMAGE_NAME}创建失败!"
  exit 1
fi
